"""
登陆相关数据模型
@author:yczha
"""
import re
from typing import Optional, Union
from pydantic import BaseModel, EmailStr, validator


class PasswordBase(BaseModel):
    password: str

    @validator('password')
    def password_len_must_between_6_20(cls, v):
        if len(v) < 6 or len(v) > 20:
            raise ValueError('密码长度必须不小于6位,不大于20位!')
        return v


class UserAuth(PasswordBase):
    username: Union[EmailStr,  int]

    @validator('username')
    def valid_phone_number(cls, v):
        if not isinstance(v, int):
            return str(v)
        elif len(str(v)) != 11 or not str(v).isdigit() or not re.match(r'^1[3|4|5|7|8]\d{9}$', str(v)):
            raise ValueError('手机号不合法!')
        return str(v)


class UserCreate(PasswordBase):
    nickname: str
    email: Optional[EmailStr]
    phone: Optional[int]
    code: Optional[int]

    @validator('phone')
    def valid_phone_number(cls, v):
        if not isinstance(v, int):
            return str(v)
        elif len(str(v)) != 11 or not str(v).isdigit() or not re.match(r'^1[3|4|5|7|8]\d{9}$', str(v)):
            raise ValueError('手机号不合法!')
        return str(v)

    @validator('code')
    def code_len_must_be_six(cls, v):
        if len(str(v)) != 6:
            raise ValueError('验证码长度必须6位!')
        return str(v)


if __name__ == '__main__':
    user_info = {'username': '18217235222', 'password': '1234569sss'}
    try:
        user = UserAuth(**user_info)
        print("Good to go!")
    except ValueError as e:
        print(e.json())
